﻿using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class WebCameraBackground : MonoBehaviour
{
    RawImage cameraImage;
    private RectTransform rectTransform;
    private WebCamTexture webCamTex;
    private int lastRotationAngle;

    IEnumerator Start()
    {
        cameraImage = GetComponent<RawImage>();
        rectTransform = GetComponent<RectTransform>();

        // 请求摄像头权限
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
        // 如果获取到摄像头权限
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            // 获取所有的摄像头设备
            WebCamDevice[] devices = WebCamTexture.devices;
            if (devices != null)
            {
                // 索引为0的摄像头一般为后置摄像头，参数分别为设备名称、图像宽度、高度、刷新率
                webCamTex = new WebCamTexture(devices[0].name, Screen.width, Screen.height, 30);
                // 实时获取摄像头的画面
                webCamTex.Play();

                cameraImage.texture = webCamTex;
            }
        }
    }

    private void Update()
    {
        if (webCamTex != null && lastRotationAngle != webCamTex.videoRotationAngle)
        {
            OnOrientationChanged();
            lastRotationAngle = webCamTex.videoRotationAngle;
        }
    }

    private void OnOrientationChanged()
    {
        // 旋转rawimage，为什么加一个负号呢？因为rawimage的z轴是背对图像的，直接使用videoRotationAngle旋转，相对于图片是逆时针旋转
        transform.localRotation = Quaternion.Euler(0, 0, -webCamTex.videoRotationAngle);

        // 判断是否是竖屏，竖屏时由于旋转的关系，需要将width和height调换
        if (webCamTex.videoRotationAngle % 180 != 0)
            rectTransform.sizeDelta = new Vector2(Screen.height, Screen.width);
        else
            rectTransform.sizeDelta = new Vector2(Screen.width, Screen.height);
    }

    private void OnGUI()
    {
        // 使用下面的旋转角度（顺时针）来旋转摄像头，以保证正确的朝向
        GUILayout.Label(webCamTex.videoRotationAngle.ToString());
        // 摄像头的视频是否垂直翻转
        GUILayout.Label(webCamTex.videoVerticallyMirrored.ToString());
    }
}
